<template>
  <div class="adevice-collectparams" style="margin-bottom:20px;">
    <h2 style="display:inline-block;">{{ selectRow.name }} 报警设置:</h2>
    <span style="font-size:12px;" v-if="showTitle"
      >（剩余电流单位：mA；温度单位：℃；电弧单位：A）</span
    >
    <Form
      v-if="showDom"
      :model="formData"
      :label-width="120"
      :rules="formRules"
      ref="collectparamsRef"
    >
      <FormItem label="A相电流告警值:" prop="a_currentVal">
        <Input v-model="formData.a_currentVal">
          <span slot="append">单位(A)</span>
        </Input>
      </FormItem>
      <FormItem label="B相电流告警值:" prop="b_currentVal">
        <Input v-model="formData.b_currentVal">
          <span slot="append">单位(A)</span></Input
        >
      </FormItem>
      <FormItem label="C相电流告警值:" prop="c_currentVal">
        <Input v-model="formData.c_currentVal">
          <span slot="append">单位(A)</span>
        </Input>
      </FormItem>
      <FormItem label="零线电流告警值:" prop="l_currentVal">
        <Input v-model="formData.l_currentVal">
          <span slot="append">单位(A)</span>
        </Input>
      </FormItem>
      <FormItem label="剩余电流告警值:" prop="s_currentVal">
        <Input v-model="formData.s_currentVal">
          <span slot="append">单位(mA)</span>
        </Input>
      </FormItem>
      <FormItem style="text-align:center;">
        <Button @click.stop.prevent="saveParams">保存</Button>
      </FormItem>
    </Form>
    <!-- 四通道 -->
    <editTable
      v-if="deviceType === 4"
      :columnsList="columnsPipe"
      v-model="tablePipe"
      @save="pipeTableSave"
    />
    <!-- 八通道 -->
    <editTable
      v-if="deviceType === 8"
      :columnsList="columnsPipe"
      v-model="tablePipe"
      @save="pipeTableSave"
    />
  </div>
</template>
<script>
import { validateDeviceId1 } from "@/utils/rules";
import {
  getAlarmSettingList,
  setAlarmSettingList,
  getDeviceParams,
  setDeviceParams,
  getDeviceDetail,
  getDeviceTypeSeries,
  getDeviceType
} from "@/api";

import editTable from "../components/editTable";
import { columnsPipe, eightTablePipe, fourTablePipe } from "../utils";
export default {
  mounted() {
    this.getInitialState().then(() => {
      this.formData.id = this.selectRow.id;
      if (this.deviceType === 1) {
        this._getAlarmSettingList();
      } else {
        this._getDeviceParams();
      }
    });
  },

  components: {
    editTable
  },
  data: () => ({
    selectRow: {},
    // tableFourPipe: [...fourTablePipe],
    // tableEightPipe: [...eightTablePipe],
    tablePipe: [],
    columnsPipe: [...columnsPipe],
    showTitle: false,
    showDom: false,
    formData: {
      id: "",
      a_currentVal: null,
      b_currentVal: null,
      c_currentVal: null,
      l_currentVal: null,
      s_currentVal: null
    },
    formRules: {
      a_currentVal: [
        {
          required: true,
          trigger: "blur",
          validator: validateDeviceId1(
            "A相电流报警值",
            "A相电流报警值只能输入大于0的数字"
          )
        }
      ],
      b_currentVal: [
        {
          required: true,
          trigger: "blur",
          validator: validateDeviceId1(
            "B相电流报警值",
            "B相电流报警值只能输入大于0的数字"
          )
        }
      ],
      c_currentVal: [
        {
          required: true,
          trigger: "blur",
          validator: validateDeviceId1(
            "C相电流报警值",
            "C相电流报警值只能输入大于0的数字"
          )
        }
      ],
      l_currentVal: [
        {
          required: true,
          trigger: "blur",
          validator: validateDeviceId1(
            "零线电流报警值",
            "零线电流报警值只能输入大于0的数字"
          )
        }
      ],
      s_currentVal: [
        {
          required: true,
          trigger: "blur",
          validator: validateDeviceId1(
            "剩余电流报警值",
            "剩余电流报警值只能输入大于0的数字"
          )
        }
      ]
    },
    deviceType: 0
  }),
  methods: {
    getInitialState() {
      const params = this.$route.params;
      return new Promise(resolve => {
        getDeviceDetail(params.id).then(res => {
          if (res.code === 200) {
            this.selectRow = res.data;
            const { deviceSeries } = res.data;
            if (deviceSeries && deviceSeries.indexOf("4路117") > -1) {
              this.deviceType = 4;
              this.showTitle = true;
              this.showDom = false;
            } else if (deviceSeries && deviceSeries.indexOf("8路117") > -1) {
              this.deviceType = 8;
              this.showTitle = true;
              this.showDom = false;
            } else {
              this.deviceType = 1;
              this.showTitle = false;
              this.showDom = true;
            }
            resolve(res.data);
          }
        });
      });
    },

    // whatTypeDevice() {
    //   return new Promise((resolve, reject) => {
    //     getDeviceType().then(res => {
    //       if (res.code === 200) {
    //         const deviceType = this.selectRow.deviceType
    //         const result = res.data.find(t => t.id === deviceType)
    //         if (result) {
    //           getDeviceTypeSeries().then(res => {
    //             const deviceType = res.data.find(t => t.id === result.seriesId)
    //             const { name } = deviceType
    //             if (name && name.indexOf("4路117") > -1) {
    //               this.deviceType = 4
    //               this.showTitle = true
    //               this.showDom = false
    //             } else if (name && name.indexOf("8路117") > -1) {
    //               this.deviceType = 8
    //               this.showTitle = true
    //               this.showDom = false
    //             } else {
    //               this.deviceType = 1
    //               this.showTitle = false
    //               this.showDom = true
    //             }
    //             resolve()
    //           })
    //         }
    //       }
    //     })
    //   })
    // },
    _getDeviceParams() {
      let that = this;
      let id = that.selectRow.id;
      let type = that.deviceType;
      let lens = 0;
      if (type === 8) {
        lens = 8;
      } else if (type === 4) {
        lens = 4;
      }

      getDeviceParams(id).then(res => {
        if (res.code == 200) {
          if (res.data.length == 0) {
            if (type === 4) {
              this.tablePipe = [...fourTablePipe];
            } else if (type === 8) {
              this.tablePipe = [...eightTablePipe];
            }
          } else {
            let resObject = res.data;

            function makeArr(array, array2) {
              let arr = [];
              for (var i = 0; i < lens; i++) {
                let b = i;
                b++;
                let obj = {
                  channel: b,
                  channelAlias: null,
                  channelType: null,
                  errorUp: null
                };
                array.forEach(t => {
                  if (t.channel == b) {
                    obj.channelAlias = t.channelAlias;
                    obj.channelType = t.channelType;
                    obj.errorUp = t.errorUp;
                  }
                });
                arr.push(obj);
              }
              return arr;
            }
            this.tablePipe = [...makeArr(resObject, eightTablePipe)];
          }
        }
      });
    },

    _getAlarmSettingList() {
      let vm = this;
      let params = {
        deviceId: vm.selectRow.id
      };
      getAlarmSettingList(params).then(res => {
        if (res.code == 200 && !!res.data) {
          vm.formData = res.data;
        }
      });
    },

    pipeTableSave(arr, i) {
      let data = arr[i];
      let { channel, channelAlias, channelType, errorUp } = data;
      if (!channel || !channelAlias || !channelType || !errorUp) {
        return false;
      }
      let params = {
        channel,
        channelAlias,
        channelType,
        errorUp,
        deviceId: this.selectRow.id
      };

      setDeviceParams(params).then(res => {
        if (res.code == 200) {
          this.$Message.success("保存成功");
          this._getDeviceParams();
        } else {
          this.$Message.error(res.message);
        }
      });
    },

    saveParams() {
      this.$refs["collectparamsRef"].validate(valid => {
        if (valid) {
          let params = {
            ...this.formData
          };
          setAlarmSettingList(params).then(res => {
            if (res.code == 200) {
              this.$Message.success("保存成功");
              this._getAlarmSettingList();
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    }
  }
};
</script>
